<template>
    <el-row class="lives-news">
        <el-row class="title">
            <h3>完善信息</h3>
        </el-row>
        <el-row>
            <el-form :inline="true">
                <el-form-item>
                    <el-button type="primary" icon="arrow-left" @click="back">返回列表</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <steps></steps>
        <el-row class="row store-content">
            <el-form :model="store" ref="store" label-width="120px">
                <el-form-item class="normal-item" label="店铺名称" prop="shopName">
                    <el-input v-model="store.shopName"></el-input>
                    <span class="tips" v-if="changed.shopName"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>修改店铺名称将会重新审核</span>
                </el-form-item>
                <el-form-item class="small-item" label="联系电话" prop="takeOutPhone">
                    <el-input v-model="store.takeOutPhone"></el-input>
                </el-form-item>
                <el-form-item class="small-item" label="联系人姓名" prop="name">
                    <el-input v-model="store.name"></el-input>
                </el-form-item>
                <el-form-item label="店铺分类" class="required">
                    <el-select class="normal-item" v-model="store.shopCategoryIdList" multiple :multiple-limit="5" placeholder="请选择店铺分类">
                        <el-option v-for="item in shopCategory" :key="item.shopCategoryId" :label="item.shopCategoryName" :value="item.shopCategoryId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="营业时间" class="required">
                    <el-radio class="radio" v-model="isAllDay" label="true">全天</el-radio>
                    <el-radio class="radio" v-model="isAllDay" label="false">自定义</el-radio>
                    <span v-if="isAllDay=='false'">
                        <el-time-select v-model="store.busBeginTime" placeholder="营业开始时间" prop="busBeginTime" :picker-options="{start: '00:00',end: '23:30',step: '00:30'}"></el-time-select>
                        <el-time-select v-model="store.busEndTime" placeholder="营业结束时间" prop="busEndTime" :picker-options="{start: '00:00',end: '23:30',step: '00:30'}"></el-time-select>
                        <b><span style="color:red;">*</span>店铺营业时间如未包含,请自行输入</b>
                    </span>
                </el-form-item>
                <el-form-item label="店铺类型" class="required">
                    <el-radio-group v-model="store.shopType">
                        <el-radio class="radio" label="RESERVE">预定</el-radio>
                        <el-radio class="radio" label="TAKEOUT">外卖</el-radio>
                        <el-radio class="radio" label="RESERVE_TAKEOUT">预定加外卖</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="配送信息" class="required">
                    <el-radio-group v-model="store.distributionType">
                        <el-radio class="radio" label="ARES">蜂鹰配送</el-radio>
                        <el-radio class="radio" label="ANUBIS">蜂鸟配送</el-radio>
                        <el-radio class="radio" label="SELF_DELIVERY_BY_MERCHANTS">商家自送</el-radio>
                    </el-radio-group>
                    <span v-if="store.distributionType == 'SELF_DELIVERY_BY_MERCHANTS'">
                        配送距离 <el-input class="small-input fee" v-model="store.distributionScope" placeholder="配送距离"></el-input>米
                        配送费 <el-input class="small-input fee" v-model="store.fee" placeholder="配送费"></el-input>元
                    </span>
                </el-form-item>
                <el-form-item label="店铺位置" class="required">
                    <el-select ref="province" v-model.number="store.provinceId" filterable placeholder="省"  @change="selectCity">
                        <el-option v-for="item in provinceList" :key="item.provinceId" :label="item.provinceName" :value="item.provinceId">
                        </el-option>
                    </el-select>
                    <el-select ref="city" v-model.number="store.cityId" filterable placeholder="市" @change="selectDistrict">
                        <el-option v-for="item in cityList" :key="item.cityId" :label="item.cityName" :value="item.cityId">
                        </el-option>
                    </el-select>
                    <el-select v-model.number="store.areaId" filterable placeholder="区/县" ref="district">
                        <el-option v-for="item in districtList" :key="item.areaId" :label="item.areaName" :value="item.areaId">
                        </el-option>
                    </el-select>
                    <el-button type="primary" @click="position">定位</el-button>
                    <span class="tips" v-if="changed.provinceId || changed.cityId || changed.areaId"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>修改店铺位置将会重新审核</span>
                </el-form-item>
                <el-form-item class="large-item" label="详细地址" prop="address">
                    <el-input v-model="store.address" placeholder="详细至街道和门牌号"></el-input>
                    <el-button class="inline-block" type="primary" @click="searchKeywords">搜索</el-button>
                    <span class="tips" v-if="changed.address"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>修改店铺地址将会重新审核</span>
                </el-form-item>
                <el-form-item>
                    <div class="amap-container">
                        <!--<el-amap-search-box class="search-box" :on-search-result="onSearchResult"></el-amap-search-box>-->
                        <el-amap ref="amap" vid="amapDemo" :plugin="plugin" class="amap" :zoom="zoom" :center="mapCenter" :events="events">
                            <el-amap-marker v-for="(marker,index) in markers" :key="index" :position="marker.position" :events="marker.events"></el-amap-marker>
                        </el-amap>
                    </div>
                </el-form-item>
                <el-form-item label="照片信息" prop="type" class="required">
                    <div class="photo-info">
                        <div class="photo-title">店铺LOGO</div>
                        <div class="photo-upload">
                            <el-upload class="upload-demo" ref="logoUrl" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadLogoUrl">
                                <img v-if="logo" :src="logo" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            <span class="tips" v-if="changed.logoUrl"><i class="fa fa-exclamation-circle" aria-hidden="true"></i>修改店铺logo将会重新审核</span>
                        </div>
                    </div>
                    <div class="photo-info">
                        <div class="photo-title">门脸照</div>
                        <div class="photo-upload">
                            <el-upload class="upload-demo" ref="shopFaceUrl" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadShopFaceUrl">
                                <img v-if="store.shopFaceUrl" :src="UPLOADURL + store.shopFaceUrl + '/shopDetail.png'" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </div>
                    </div>
                    <div class="photo-info">
                        <div class="photo-title">店内照片</div>
                        <div class="photo-upload">
                            <el-upload class="upload-demo" ref="shopInnerUrl" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadShopInnerUrl">
                                <img v-if="store.shopInnerUrl" :src="UPLOADURL + store.shopInnerUrl + '/shopDetail.png'" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row class="btn-row row">
            <el-col class="tac">
                <router-link to="/shopList">
                    <el-button size="large">返回上一步</el-button>
                </router-link>
                <el-button class="small-item" type="primary" size="large" @click="showStore">进行下一步</el-button>
            </el-col>
        </el-row>
    </el-row>
</template>
<script>
	import {getShopCategoryList, saveShopBaseInfo, getShopBaseInfo, uploadFiles, setShopLogo} from '@/api/api';
	import {getProvinceList, getCityList, getDistrictList,} from '@/api/region';
	import steps from '@/views/steps/steps'
	export default {
		name: 'index1',
		components: {
			steps: steps,
		},
		data() {
			var that = this;
			return {
                changed: {
	                shopName: false,
	                logoUrl: false,
	                address: false,
	                provinceId: false,
	                cityId: false,
	                areaId: false,
                },
				oldValue:{
					shopName: null,
                    logoUrl: null,
                    address: null,
					provinceId: null,
					cityId: null,
					areaId: null,
                },
				store: {
					address: null,
					areaId: null,
                    areaName: null,
					audit: null,
					busBeginTime: null,
					busEndTime: null,
					cityId: null,
                    cityName: null,
					fee: 0,
					distributionScope: 0,
					latitude: 0,
					logoUrl: null,
					longitude: 0,
					name: null,
					provinceId: null,
                    provinceName: null,
					shopCategoryIdList: [],
					shopFaceUrl: null,
					shopInnerUrl: null,
					shopName: null,
					shopType: null,
					distributionType: null,
					takeOutPhone: null
				},
                shopId: null,
				logo: '',
				isAllDay: 'true',
				province: [],
				city: [],
				district: [],
				zoom: 14,
				mapCenter: [0, 0],
				markers: [],
				plugin: [{
					pName: 'ToolBar',
					position: 'RT'
				}, {
					pName: 'Geolocation',
					events: {
						init(o) {
							o.getCityInfo((status, result) => {
								that.mapCenter = result.center;
								that.$nextTick();
							})
						}
					}
				}],
				events: {
					click: function(e) {
						var lnglat = e.lnglat;
						that.store.longitude = lnglat.lng;
						that.store.latitude = lnglat.lat;
						that.markers = [{
							position: [e.lnglat.lng, e.lnglat.lat],
							events: {
								click: function(e) {
									var geocoder = new AMap.Geocoder({
										city: that.store.cityId
									});
									geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
										if (status === 'complete' && result.info === 'OK') {
											if (result && result.regeocode) {
												that.store.address = result.regeocode.formattedAddress
											}
										}
									});
								}
							}
						}];
						var geocoder = new AMap.Geocoder({
							city: that.store.cityId
						});
						geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
							if (status === 'complete' && result.info === 'OK') {
								if (result && result.regeocode) {
									that.store.address = result.regeocode.formattedAddress
								}
							}
						});
					}
				},
				shopCategory: [],
				provinceList: [],
				cityList: [],
				districtList: [],
				backUrl: ''
			};
		},
		created: function() {
			var shopId = parseInt(this.$route.query.shopId);
			this.backUrl = this.$route.query.backUrl;
			this.shopId = shopId;
			getShopCategoryList().then(res => {
				console.log(res);
				this.shopCategory = res.list;
			});
			getProvinceList().then(res => {
				this.provinceList = res;
			});
            getShopBaseInfo(shopId).then(res => {
					console.log(res);
					this.store = {
						address: res.detail.address || null,
						areaId: res.detail.areaId || null,
						areaName: res.detail.areaName || null,
						audit: res.detail.audit || null,
						busBeginTime: res.detail.busBeginTime || null,
						busEndTime: res.detail.busEndTime || null,
						cityId: res.detail.cityId || null,
						cityName: res.detail.cityName || null,
						fee: res.detail.fee || 0,
						distributionScope:  res.detail.distributionScope || 0,
						latitude: res.detail.latitude || 0,
						logoUrl: res.detail.logoUrl,
						longitude: res.detail.longitude || 0,
						name: res.detail.name || null,
						provinceId: res.detail.provinceId || null,
						provinceName: res.detail.provinceName || null,
						shopCategoryIdList: res.shopCategoryIdList || [],
						shopFaceUrl: res.detail.shopFaceUrl || null,
						shopInnerUrl: res.detail.shopInnerUrl || null,
						shopName: res.detail.shopName || null,
						shopType: res.detail.shopType,
						distributionType: res.detail.distributionType || null,
						takeOutPhone: res.detail.takeOutPhone || null
					};

					this.oldValue = {
						shopName: res.detail.shopName || null,
						logoUrl: res.detail.logoUrl || null,
						address: res.detail.address || null,
						provinceId: res.detail.provinceId || null,
						cityId: res.detail.cityId || null,
						areaId: res.detail.areaId || null,
					};

					this.logo = res.detail.logoUrl? this.UPLOADURL + res.detail.logoUrl + '/shopDetail.png' : '';
					if (res.detail.busBeginTime == '00:00' & res.detail.busEndTime == '23:59:59') {
						this.isAllDay = 'true';
					} else {
						this.isAllDay = 'false';
					}
					if (res.detail.latitude && res.detail.longitude) {
						this.mapCenter = [res.detail.longitude, res.detail.latitude];
						this.markers = [{
							position: [res.detail.longitude, res.detail.latitude]
						}];
					}
				})


		},
        watch: {
	        'store.shopName': function(newVal, oldVal){
	        	if(!this.oldValue.shopName){
	        		return
                }
	        	this.changed.shopName = this.oldValue.shopName != newVal;
	        },
            'store.logoUrl': function(newVal, oldVal){
	        	if(!this.oldValue.logoUrl){
	        		return
                }
	            this.changed.logoUrl = this.oldValue.logoUrl != newVal;
	        },
            'store.address': function(newVal, oldVal){
	        	if(!this.oldValue.address){
	        		return
                }
	            this.changed.address = this.oldValue.address != newVal;
	        },
            'store.provinceId': function(newVal, oldVal){
	        	if(!this.oldValue.provinceId){
	        		return
                }
	            this.changed.provinceId = this.oldValue.provinceId != newVal;
                if(oldVal){
	                if (newVal == oldVal) {
		                return;
	                }
	                this.store.cityId = null;
	                this.store.areaId = null;

	                this.cityList = [];
	                this.districtList = [];
	                console.log(newVal);
	                if(newVal){
		                getCityList(newVal).then(res => {
			                this.cityList = res;
			                console.log(this.cityList);
		                })
	                }
                }

            },
            'store.cityId': function(newVal, oldVal){
	        	if(!this.oldValue.cityId){
	        		return
                }
	            this.changed.cityId = this.oldValue.cityId != newVal;
	        	if(oldVal){
			        if (newVal == oldVal) {
				        return;
			        }

			        this.store.areaId = null;

			        this.districtList = [];
			        console.log(newVal);
			        if(newVal){
				        console.log(newVal);
				        getDistrictList(newVal).then(res => {
					        this.districtList = res;
					        console.log(this.districtList);

				        })
			        }
		        }
	        },
            'store.areaId': function(newVal, oldVal){
	        	if(!this.oldValue.areaId){
	        		return
                }
	            this.changed.areaId = this.oldValue.areaId != newVal;
	        }
        },
		methods: {
			back: function(){
				this.$router.push('/'+this.backUrl);
			},
			selectCity: function() {
				getCityList(this.store.provinceId).then(res => {
					this.cityList = res;
				})
			},
			selectDistrict: function() {
				if(this.store.cityId){
					getDistrictList(this.store.cityId).then(res => {
						this.districtList = res;
					})
                }

			},
			onSearchResult: function(pois) {
				var that = this;
				let latSum = 0;
				let lngSum = 0;
				if (pois.length > 0) {
					pois.forEach(poi => {
						let { lng, lat } = poi;
						lngSum += lng;
						latSum += lat;
						that.markers.push({
							position: [lng, lat],
							events: {
								click: function(e) {
									var geocoder = new AMap.Geocoder();
									geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
										if (status === 'complete' && result.info === 'OK') {
											if (result && result.regeocode) {
												that.store.address = result.regeocode.formattedAddress
											}
										}
									});
								}
							}
						});
					});
					let center = {
						lng: lngSum / pois.length,
						lat: latSum / pois.length
					};
					this.mapCenter = [center.lng, center.lat];
				}
			},
			position: function() {
				var that = this;
				if (!that.store.cityId) {
					console.log('no cityId');
					that.$message({
						type: 'error',
						message: '请选择店铺所在省-市-区后再搜索'
					})
					return;
				}
				//行政区域搜索
//				var district = new AMap.DistrictSearch({
//					level: 'district',
//					subdistrict: 0,
//					showbiz: false
//				});
				var geocoder = new AMap.Geocoder();

				geocoder.getLocation(that.$refs.province.query + that.$refs.city.query + that.$refs.district.query, function(status, result) {
					console.log(result);
					if (status === 'complete' && result.info === 'OK') {
						var districtList = result.geocodes;
						that.mapCenter = [districtList[0]['location'].lng, districtList[0]['location'].lat];
					}
				});
			},
			searchKeywords: function(){
				var that = this;
				if (!that.store.cityId) {
					console.log('no cityId');
					that.$message({
						type: 'error',
						message: '请选择店铺所在省-市-区后再搜索'
					});

					return;
				}

				var placeSearch = new AMap.PlaceSearch({
                    city: that.store.cityId
                });
				placeSearch.search(that.store.address, function (status, result) {
                    console.log(status,result);
                    if(status === 'complete' && result.info === 'OK'){
                    	var poiList = result.poiList.pois;
                    	var amap = that.$refs.amap.$$getInstance();
                    	amap.setZoomAndCenter(16,[poiList[0]['location'].lng, poiList[0]['location'].lat])
	                    that.markers = [];
	                    poiList.forEach((item,index) => {
		                    that.markers.push({
			                    position: [item.location.lng, item.location.lat],
			                    events: {
				                    click: function(e) {
					                    var geocoder = new AMap.Geocoder();
					                    geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
						                    if (status === 'complete' && result.info === 'OK') {
							                    if (result && result.regeocode) {
								                    that.store.address = result.regeocode.formattedAddress
							                    }
						                    }
					                    });
				                    }
			                    }
		                    });
	                    })
                    }
				})
            },
			showStore: function() {

				if(!this.store.shopName){
					this.$message({
						type: 'error',
						message: '请输入店铺名称'
					});
					return;
				}
				if(!this.store.takeOutPhone){
					this.$message({
						type: 'error',
						message: '请填写联系人电话'
					});
					return;
				}
				if(!this.store.name){
					this.$message({
						type: 'error',
						message: '请填写联系人姓名'
					});
					return;
				}
				if(this.store.shopCategoryIdList.length == 0){
					this.$message({
						type: 'error',
						message: '请选择店铺分类'
					});
					return;
				}
				if(!this.store.shopType){
					this.$message({
						type: 'error',
						message: '请选择店铺类型'
					});
					return;
				}
				if(!this.store.provinceId){
					this.$message({
						type: 'error',
						message: '请选择省份'
					});
					return;
				}
				if(!this.store.cityId){
					this.$message({
						type: 'error',
						message: '请选择市'
					});
					return;
				}
				if(!this.store.areaId){
					this.$message({
						type: 'error',
						message: '请选择区域'
					});
					return;
				}
				if(!this.store.address){
					this.$message({
						type: 'error',
						message: '请填写详细地址'
					});
					return;
				}
				if(!this.store.logoUrl){
					this.$message({
						type: 'error',
						message: '请上传店铺logo'
					});
					return;
				}
				if(!this.store.shopFaceUrl){
					this.$message({
						type: 'error',
						message: '请上传门脸照'
					});
					return;
				}
				if(!this.store.shopInnerUrl){
					this.$message({
						type: 'error',
						message: '请上传店内照片'
					});
					return;
				}
				if(this.store.latitude == 0 && this.store.longitude == 0){
					this.$message({
						type: 'error',
						message: '请地图上选择店铺位置'
					});
					return;
				}

				if (this.isAllDay == 'true') {
					this.store.busBeginTime = '00:00:00';
					this.store.busEndTime = '23:59:59';
				} else if(!this.store.busBeginTime){
					this.$message({
						type: 'error',
						message: '请选择营业开始时间'
					});
					return;
				} else if(!this.store.busEndTime){
					this.$message({
						type: 'error',
						message: '请选择营业结束时间'
					});
					return;
				}

				if(this.store.distributionType == 'SELF_DELIVERY_BY_MERCHANTS'){
					if(this.store.distributionScope <1){
						this.$message({
							type: 'error',
							message: '配送距离必须大于0'
						});
						return
                    }
                }

				//营业时间比较
				var busBeginTime = this.formatSeconds(this.store.busBeginTime);
				var busEndTime = this.formatSeconds(this.store.busEndTime);
				console.log(busBeginTime);
				console.log(busEndTime);

                if(busBeginTime > busEndTime){
	                this.$message({
		                type: 'error',
		                message: '营业开始时间不能大于结束时间'
	                });
	                return;
                }
				if(parseFloat(this.store.fee) < 0){
					this.$message({
						type: 'error',
						message: '配送费不能小于0'
					});
					return;
                }

				this.store.provinceName = this.$refs.province.query;
				this.store.cityName = this.$refs.city.query;
				this.store.areaName = this.$refs.district.query;
				console.log(this.store);
				saveShopBaseInfo(this.shopId,this.store).then(res => {
					console.log(res);
					this.$router.push({ path: 'step2?backUrl=' + this.backUrl + '&shopId=' + this.shopId, query: { step: '1' } })
				})

			},
			uploadLogoUrl: function(e) {
				console.log(e);
				var file = e.raw;
				var fd = new FormData();
				fd.append('file', file);
				fd.path = '/store';
				setShopLogo(this.shopId,fd).then(data => {
					console.log(data);
					this.logo = e.url;
					this.store.logoUrl = data;
				}).catch(err => {
					console.log(err)
				})
			},
			uploadShopFaceUrl: function(e) {
				var file = e.raw;
				var fd = new FormData();
				fd.append('file', file);
				fd.path = '/store';
				uploadFiles(fd).then(data => {
					console.log(data)
					this.store.shopFaceUrl = data.originalUrl;
				}).catch(err => {
					console.log(err)
				})
			},
			uploadShopInnerUrl: function(e) {
				var file = e.raw;
				var fd = new FormData();
				fd.append('file', file);
				fd.path = '/store';
				uploadFiles(fd).then(data => {
					console.log(data)
					this.store.shopInnerUrl = data.originalUrl;
				}).catch(err => {
					console.log(err)
				})
			},
            formatSeconds: function (time) {
                var arr = time.split(':');
                console.log(arr);
                var formatTime = 0;
                if(arr[0]){
                	formatTime += parseInt(arr[0])*60*60;
                }
                if(arr[1]){
	                formatTime += parseInt(arr[1])*60;
                }
	            if(arr[2]){
		            formatTime += parseInt(arr[2]);
	            }

	            return formatTime;
            }

		},

	}

</script>
<style scoped lang="scss">
    .lives-news {
        .title {
            font-size: 12px;
            border-bottom: 1px solid #eaeaea;
            margin-bottom: 5px;
            h3 {
                display: inline-block;
                padding: 5px 0;
                margin: 0;
                font-weight: normal;
                color: #23b7e5;
                border-bottom: 1px solid #23b7e5;
            }
        }
        .label-color {
            color: red;
        }
        img{
            vertical-align: middle;
            height: 120px;
        }
        .settlement{
            margin: 15px 0;
        }

        .store-content {
            background-color: #fff;
            padding: 40px 50px;
            min-height: 650px;
        }

        .fee {
            width: 300px;
        }

        .amap-container {
            position: relative;
            height: 500px;
        }

        .search-box {
            position: absolute;
            top: 15px;
            left: 10px;
        }

        .photo-info {
            width: 600px;
            /* height: 80px; */
            border-bottom: 1px solid #eee;
        }

        .photo-title,
        .photo-upload {
            display: inline-block;
            vertical-align: middle;
        }

        .photo-title {
            width: 90px;
            height: 100%;
            line-height: 90px;
            text-align: center;
            font-size: 12px;
            background-color: #dedede;
            color: #666;
        }

        .upload-demo {
            width: 100px;
            /*height: 60px;*/
            height: 90px;
            margin-left: 10px;
            vertical-align: middle;
            overflow: hidden;
            /*background-color: #dedede;*/
            border: 1px dashed #dedede;
            border-radius: 5px;
            display: inline-flex;
            flex-direction: row;
            align-items: center;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100px;
            height: 60px;
            line-height: 60px;
            text-align: center;
            vertical-align: middle;
        }

        .avatar {
            width: 100%;
            height: 100%;
            display: block;
        }
        .el-input{
            width: 400px;
        }
        .small-input{
            width: 80px;
        }
        .el-date-editor.el-input{
            width: 193px;
        }

        .tips{
            font-size: 14px;
            color: #fdba4d;
        }

    }

</style>
